﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.EntityFrameworkCore;
using Nuanyang.Asp.Net.Core.Extension.DataBase;
using Nuanyang.Asp.Net.Core.Extension.Entities;
using Nuanyang.Asp.Net.Core.Extension.Utils;

namespace Nuanyang.Asp.Net.Core.Extension
{
    public static class EndpointsExtension
    {
        internal static FunctionContext Context { get; private set; }

        /// <summary>
        /// 添加Function到权限表
        /// </summary>
        /// <param name="endpointRouteBuilder"></param>
        /// <returns></returns>
        public static IEndpointRouteBuilder AddFunction(this IEndpointRouteBuilder endpointRouteBuilder, FunctionContext functionContext)
        {
            //连接数据库
            Context = functionContext;
            //迁移数据库
            Context.Database.Migrate();
            //导入数据
            List<FunctionEntity> list = new List<FunctionEntity>();
            FunctionEntity functionEntity = null;
            foreach (var item in endpointRouteBuilder.DataSources)
            {
                foreach (var endPoint in item.Endpoints)
                {                   
                    if (Context.Function.FirstOrDefault(c => c.FunctionName == endPoint.DisplayName) != null)
                    {
                        continue;
                    }
                    functionEntity = new FunctionEntity();
                    functionEntity.FunctionName = endPoint.DisplayName;
                    functionEntity.DisplayName = endPoint.DisplayName;
                    var name = endPoint.Metadata.FirstOrDefault(c => c.GetType() == typeof(RouteNameMetadata));
                    if (name != null)
                    {
                        functionEntity.DisplayName = ((RouteNameMetadata)name).RouteName;
                    }
                    RoutePattern routePattern = endPoint.GetType().GetProperty(nameof(RoutePattern)).GetValue(endPoint) as RoutePattern;
                    functionEntity.FunctionRouting = routePattern.RawText;
                    list.Add(functionEntity);
                }
            }
            Context.Function.AddRange(list);
            Context.SaveChanges();
            return endpointRouteBuilder;
        }

        
    }
}
